package com.juneng.service.impl;

import com.alipay.api.AlipayResponse;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juneng.common.Condition;
import com.juneng.common.R;
import com.juneng.dto.AfterSalesServiceRequest;
import com.juneng.entity.*;
import com.juneng.mapper.OrderMsgMapper;
import com.juneng.mapper.OrderRefundMapper;
import com.juneng.utils.BeanCopyUtils;
import com.juneng.mapper.OrderUserMapper;
import com.juneng.service.IOrderUserService;
import com.juneng.dto.OrderUserDto;
import com.juneng.dto.OrderUserQueryDto;
import com.juneng.utils.CompareUtil;
import com.juneng.utils.PayUtil;
import com.juneng.utils.RandomUtils;
import com.juneng.utils.wechat.WXPayUtil;
import com.juneng.vo.OrderUserVo;
import com.mchange.lang.IntegerUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户订单表 服务实现类
 *
 * @author zds
 * @since 2021-07-26
 */
@Service
@AllArgsConstructor
@Slf4j
public class OrderUserServiceImpl implements IOrderUserService {

    protected OrderUserMapper orderUserMapper;

    protected OrderRefundMapper orderRefundMapper;

    protected ObjectMapper objectMapper;

    protected OrderMsgMapper orderMsgMapper;


    /**
     * 订单分页  confirmDelivery
     * @param dto
     * @return
     */
    @Override
    public IPage<OrderUserVo> page(OrderUserQueryDto dto) {
        IPage<OrderUserVo> page = Condition.getPage(dto);
        IPage<OrderUserVo> page1 = orderUserMapper.page(page, dto);
        List<OrderUserVo> records = page1.getRecords();
        for (OrderUserVo record : records) {
            List<OrderMsg> orderMsgs = orderMsgMapper.selectList(new LambdaQueryWrapper<OrderMsg>().eq(OrderMsg::getInternalOrder, record.getInternalOrder()));
            record.setProduct(orderMsgs);
        }
        return page1;
    }

    @Override
    public List<OrderUser> list(OrderUserQueryDto dto) {
        QueryWrapper<OrderUser> queryWrapper = new QueryWrapper<>(BeanCopyUtils.copy(dto,OrderUser.class));
        return orderUserMapper.selectList(queryWrapper);
    }

    @Override
    public Integer save(OrderUserDto dto) {
        return orderUserMapper.insert(BeanCopyUtils.copy(dto,OrderUser.class));
    }

    @Override
    public Integer updateById(OrderUserDto dto) {
        OrderUser orderUser = new OrderUser();
        orderUser.setStatus(dto.getStatus());
        orderUser.setDeliveryCompany(dto.getDeliveryCompany());
        orderUser.setDeliverySn(dto.getDeliverySn());
        QueryWrapper<OrderUser> wrapper = new QueryWrapper<>();
        wrapper.eq("internal_order",dto.getInternalOrder());
        if (dto.getRefundState() != null){
            //修改退货表 confirm
            OrderRefund orderRefund = new OrderRefund();
            orderRefund.setRefundState(dto.getRefundState());
            int update = orderRefundMapper.update(orderRefund, new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getInternalOrder, dto.getInternalOrder()));
        }
        return orderUserMapper.update(orderUser, wrapper);
    }

    @Override
    public Integer deleteLogic(List<Integer> toIntList) {
        return orderUserMapper.deleteBatchIds(toIntList);
    }

    @Override
    public OrderUser getById(Integer id) {
        return orderUserMapper.selectById(id);
    }

    /**
     * 售后服务
     * @param request
     * @return
     */
    @Override
    public R<?> AfterSalesServiceRequest(HttpServletRequest request, HttpServletResponse response, AfterSalesServiceRequest request1) {
        try {
            // 生成内部订单号 internal_order
            String orderIdByUUId = RandomUtils.getOrderIdByUUId();
            //退款方式
            if (request1.getPaymentType() == 0){
                log.info("--------------------------------------"+"调起支付宝退款"+ "支付宝支付订单号："+ request1.getPayOrder()+ "/支付宝支付路内部订单号："+request1.getInternalOrder()+"--------------------------------------");
                //支付宝退款
                String getpay = PayUtil.aliRefund(request1.getInternalOrder(), request1.getPayOrder(), request1.getRefundAmount(), request1.getRefundAmount());
                GetAlipay payReture = objectMapper.readValue(getpay, GetAlipay.class);
                 if (payReture.getAlipay_trade_refund_response().getMsg().equals("Success")){
                     log.info("--------------------------------------"+"退款成功"+ "支付宝支付订单号："+ request1.getPayOrder()+ "/支付宝支付路内部订单号："+request1.getInternalOrder()+"--------------------------------------");
                     //修改订单状态
                     QueryWrapper<OrderUser> wrapper1 = new QueryWrapper<>();
                     wrapper1.eq("internal_order",request1.getInternalOrder());
                     OrderUser orderUser = new OrderUser();
                     orderUser.setStatus(12);
                     int update1 = orderUserMapper.update(orderUser, wrapper1);
                     OrderRefund orderRefund = new OrderRefund();
                     orderRefund.setRefundState(2);
                     orderRefundMapper.update(orderRefund,new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getInternalOrder,request1.getInternalOrder()));
                       return R.success("退款成功");
                 }else {
                     log.info("--------------------------------------"+ "支付宝支付订单号："+ request1.getPayOrder()+ "/支付宝支付路内部订单号："+request1.getInternalOrder()+ "--------------------------------------");
                     return R.failed("微信退款失败");
                 }
            }else {
                log.info("--------------------------------------"+"调起微信退款"+ "微信支付订单号："+ request1.getPayOrder()+ "/微信支付路内部订单号："+request1.getInternalOrder()+"--------------------------------------");
                //微信退款
                Map<String, String> reimburse = WXPayUtil.getReimburse(request, response, request1.getPayOrder(), request1.getInternalOrder(), orderIdByUUId, request1.getPayAmount(), request1.getRefundAmount(),request1.getRefundReason());
                OrderRefund orderRefund = new OrderRefund();
                orderRefund.setOutRefundNo(orderIdByUUId);
                QueryWrapper<OrderRefund> wrapper = new QueryWrapper<>();
                wrapper.eq("internal_order",request1.getInternalOrder());
                if (reimburse.get("return_code").equals("SUCCESS")){ //微信退款成功
                    orderRefund.setRefundState(2);
                    int update = orderRefundMapper.update(orderRefund, wrapper);
                    //修改订单状态
                    QueryWrapper<OrderUser> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("internal_order",request1.getInternalOrder());
                    OrderUser orderUser = new OrderUser();
                    orderUser.setStatus(12);
                    int update1 = orderUserMapper.update(orderUser, wrapper1);
                    return R.success("微信退款成功");
                }else {
                    log.info("--------------------------------------"+ "微信支付订单号："+ request1.getPayOrder()+ "/微信支付路内部订单号："+request1.getInternalOrder()+ "--------------------------------------");
                    int update = orderRefundMapper.update(orderRefund, wrapper);
                    //修改订单状态
                    QueryWrapper<OrderUser> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("internal_order",request1.getInternalOrder());
                    OrderUser orderUser = new OrderUser();
                    orderUser.setStatus(12);
                    int update1 = orderUserMapper.update(orderUser, wrapper1);
                    return R.failed("微信退款失败");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            R.failed("支付失败");
        }

        return null;
    }

    /**
     * 订单下载
     * @param dto
     * @return
     */
    @Override
    public void orderDownload(OrderUserQueryDto dto,HttpServletResponse response) {
        //声明输出流
        OutputStream os = null;
        IPage<OrderUserVo> page = Condition.getPage(dto);
        IPage<OrderUserVo> page1 = orderUserMapper.page(page, dto);
        List<OrderUserVo> records = page1.getRecords();
        for (OrderUserVo record : records) {
            List<OrderMsg> orderMsgs = orderMsgMapper.selectList(new LambdaQueryWrapper<OrderMsg>().eq(OrderMsg::getInternalOrder, record.getInternalOrder()));
            record.setProduct(orderMsgs);
        }
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook sheets = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = sheets.createSheet("订单表一");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = sheets.createCellStyle();
        /*style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式*/
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("内部订单号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("支付订单号");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("支付方式");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("订单金额");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("支付金额");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("收货人电话");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("收货地址");
        cell.setCellStyle(style);
        cell = row.createCell(7);
        cell.setCellValue("收货详细地址");
        cell.setCellStyle(style);
        cell = row.createCell(8);
        cell.setCellValue("订单进度");
//        cell.setCellStyle(style);
//        cell = row.createCell(9);
//        cell.setCellValue("商品详细");
        for (int i = 0; i < records.size(); i++) {
            row = sheet.createRow(i + 2);
            row.createCell(0).setCellValue(records.get(i).getInternalOrder());//内部订单号
            row.createCell(1).setCellValue(records.get(i).getPayOrder());//支付订单号
            row.createCell(2).setCellValue(records.get(i).getStatus());//支付方式
            row.createCell(3).setCellValue(records.get(i).getTotalAmount().toString());//订单金额
            row.createCell(4).setCellValue(records.get(i).getPayAmount().toString());//支付金额
            row.createCell(5).setCellValue(records.get(i).getConsigneePhone());//收货人电话
            row.createCell(6).setCellValue(records.get(i).getConsigneeAddress());//收货地址
            row.createCell(7).setCellValue(records.get(i).getConsigneeAddressDetail());//收货详细地址
            row.createCell(8).setCellValue(records.get(i).getStatus());//订单进度
          //  row.createCell(9).setCellValue(records.get(i).getProduct().toString()); //商品详情]

        }
        // 第六步，将文件存到指定位置
        try
        {
            //列宽自适应
            for (int i = 0; i <= 11; i++) {
                sheet.autoSizeColumn(i);
            }
            //获取输出流
            os = response.getOutputStream();
            String title= "company";
            String  fileName = new String(title.getBytes("GB2312"), "ISO_8859_1");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            sheets.write(os);
//            os.flush();
//            os.close();
//            String title= "company";
//            String  fileName = new String(title.getBytes("GB2312"), "ISO_8859_1");
//            fileName = URLEncoder.encode(fileName,"utf-8");
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            OutputStream os = response.getOutputStream();
//           // FileOutputStream fout = new FileOutputStream("/Users/mac/Desktop/code" + fileName+".xls");
//            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xls");//默认Excel名称
//            sheets.write(os);
//            os.flush();
//            os.close();
//            Date date = new Date();
//            String str = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSSS").format(date); //需要文件导出带有时间的，请把时间拼接到/杠后面去
//            FileOutputStream fout = new FileOutputStream("/Users/mac/Desktop/code" + str + "Table.xls");
//            sheets.write(fout);
//            fout.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                // 关闭输出流
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 列表
     * @param dto
     * @return
     */
    @Override
    public List<OrderUserVo> getOrderUserList(OrderUserQueryDto dto) {
        List<OrderUserVo> orderUserList = orderUserMapper.getOrderUserList(dto);
        for (OrderUserVo orderUserVo : orderUserList) {
            List<OrderMsg> orderMsgs = orderMsgMapper.selectList(new LambdaQueryWrapper<OrderMsg>().eq(OrderMsg::getInternalOrder, orderUserVo.getInternalOrder()));
            orderUserVo.setProduct(orderMsgs);
        }
        return orderUserList;
    }
}
